<?php

namespace app\common\model\xilumarket;

use app\common\library\Auth;
use think\Db;
use think\Log;
use think\Model;
use function fast\array_get;


class UserCollection extends Model
{

    const TYPE_PRODUCT = 1;
    const TYPE_FORUM = 2;


    // 表名
    protected $name = 'xilumarket_user_collection';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function forum(){
        return $this->belongsTo(TopicForum::class,'collection_id','id',[],'inner')->setEagerlyType(0);
    }

    public function product(){
        return $this->belongsTo(Product::class,'collection_id','id',[],'inner')->setEagerlyType(0);
    }

    /**
     * @param int $userId
     * @param int $recordId
     * @param $type
     * @return bool|string true是已收藏状态, false是未收藏状态
     */
    public static function toggleCollection($userId, $recordId, $type) {
        Db::startTrans();
        try {
            $model = static::where('user_id', $userId)
                ->where('collection_type', $type)
                ->where('collection_id', $recordId)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new UserCollection([
                    'user_id' => $userId,
                    'collection_type' => $type,
                    'collection_id' => $recordId
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    return $model->getError();
                }
                $result = true;
            }
            $collectionCount = UserCollection::where('collection_type', $type)->where('collection_id', $recordId)->count();
            switch ($type) {
                case self::TYPE_PRODUCT:
                    Product::where('id', $recordId)->update(['collection_count' => $collectionCount]);
                    break;
                case self::TYPE_FORUM:
                    TopicForum::where('id', $recordId)->update(['collection_count' => $collectionCount]);
                    break;
            }
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            Db::rollback();
            return false;
        }
        Db::commit();
        return $result;
    }

    /**
     * 我的收藏列表-商品
     */
    public static function productLists($params,$user_id){
        $pagesize = array_get($params,'pagesize',10);

        return Product::alias('product')
            ->join("xilumarket_user_collection user_collection",'user_collection.collection_id=product.id')
            ->order("user_collection.id",'desc')
            ->field(['product.id','product.user_id','product.want_num','product.name','product.content','product.thumb_image','product.salesprice','user_collection.createtime'])
            ->where('user_collection.user_id',$user_id)
            ->where('user_collection.collection_type',self::TYPE_PRODUCT)
            ->paginate($pagesize)
            ->each(function ($row){
                $row->relationQuery(['user'=>function($q){
                    $q->withField(['id','nickname','avatar']);
                }]);
            });
    }

    /**
     * 我的收藏列表-帖子
     */
    public static function forumLists($params,$user_id){
        $pagesize = array_get($params,'pagesize',10);

        return TopicForum::alias("topic_forum")
            ->join("xilumarket_user_collection user_collection",'user_collection.collection_id=topic_forum.id')

            ->order("user_collection.id",'desc')
            ->field(['topic_forum.id','topic_forum.user_id','topic_forum.content','topic_forum.topic_id','topic_forum.images','topic_forum.fav_count','topic_forum.comment_count','topic_forum.collection_count','topic_forum.createtime'])
            ->where('user_collection.user_id',$user_id)
            ->where('user_collection.collection_type',self::TYPE_FORUM)
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->relationQuery([
                    'user'=>function($query){$query->withField(['id','nickname','avatar']);}
                ]);
                $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                    $query->where('user_id',$user_id);
                },
                ]);
                $row->relationCount($row,['isFav'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
                }]);
                $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
                }]);
            });

//        return static::with(['forum'=>function($q){
//            $q->withField(['id','content','topic_id','images','fav_count','comment_count','collection_count','createtime']);
//        }])->where('user_collection.user_id',$user_id)
//            ->where('collection_type',self::TYPE_FORUM)
//            ->order('id','desc')
//            ->paginate($pagesize);
    }

    /**
     * 用户是否已收藏
     * @param $userId
     * @param $recordId
     * @param $type
     * @return bool
     */
    public static function isFav($userId, $recordId, $type) {
        if(!$userId || !$recordId || !$type)
            return false;
        return static::where('user_id',$userId)
                ->where('collection_type',$type)
                ->where('collection_id',$recordId)->count() ? 1 : 0;
    }

    /**
     * 收藏数量
     * @param $user Object
     * @param $type array
     * @return int|string
     * @throws \think\Exception
     */
    public static function getCollectionCount($user,$type){
        return self::where('user_id',$user->id)->whereIn('collection_type',$type)->count();

    }

}
